package com.ebelter.temperaturegun.ui.view.temview;


import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.animation.LinearInterpolator;


import com.ebelter.btcomlib.utils.DipUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;

import java.util.ArrayList;
import java.util.List;

public class TemHisChartViewForm extends View {

    private static final String TAG = "TemHisChartViewForm";
    public TemHisChartViewForm(Context context) {this(context,null);}

    public TemHisChartViewForm(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }





    private List<TemHisChartView.ItemBean> datas;

    private int selectIndex = -1;//选中的角标


    public int getSelectIndex() {
        return selectIndex;
    }

    public void setSelectIndex(int selectIndex,boolean iSinvalidate) {
        if (datas!=null){
            if (datas.size()>0&&selectIndex>=datas.size()){
                selectIndex=datas.size()-1;
            }
            if (selectIndex<0){
                selectIndex=0;
            }
            this.selectIndex = selectIndex;
            if (iSinvalidate){
                invalidate();
                if (itemSelectListener!=null)itemSelectListener.selectChange(selectIndex,datas.get(selectIndex));
            }
        }


    }
    public void setSelectIndex(int selectIndex) {
        setSelectIndex(selectIndex,true);
    }

    public int dp1;

    private int topHeight;//顶部高度
    private int middleHeight;
    private int buttomHeight;

    int mWidth;//整个控件的宽度
    int mHeight;//整个控件的高度
    Paint mPaint;
    Paint mPaint2;

    private float middleItemHeght;//方格的高度值

    private void init(Context context) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//抗锯齿
        mPaint.setStrokeWidth(dp1);

        mPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);//抗锯齿
        mPaint2.setStrokeWidth(dp1*3);

        dp1 = DipUtil.dip2px(getContext(),1);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        initBaseData(true);

    }

    private void initBaseData(boolean is20) {

        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();

        topHeight= (int) (mHeight*TemHisChartView.TopHeightWeight);
        buttomHeight= (int) (mHeight*TemHisChartView.ButtomHeightWeight);
        middleHeight= mHeight-topHeight-buttomHeight;


        middleItemHeght = middleHeight / TemHisChartView.Y_ITEMS_C.length;//计算出item的高度

        if (is20){
            xInit = 0;
        }

        if (datas!=null){
            minXInit = 0;
            maxXInit = TemHisChartView.ItemIntervalWeight * (datas.size()+5)-mWidth;
        }


        out("---initBaseData--mWidth = "+mWidth+"--mHeight = "+mHeight+"---topHeight="+topHeight+"---middleHeight="+middleHeight+"---"+buttomHeight);
    }


    private static final int huiBanColor= Color.parseColor("#4B5774");
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        out("-----------onDraw--Start");

        //画上半部分的黑色面板
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(huiBanColor);//暗灰色面板
        canvas.drawRect(0,0,mWidth,topHeight + middleHeight,mPaint);

        //画下半部分的颜色面板
        drawButtomBg(canvas);//画底部背景

        drawForm(canvas);//画表格

        if (datas!=null&&datas.size()>0){
            drawDatas(canvas,datas);
        }





    }

    private static final int ButtomBgColor= Color.parseColor("#202737");
    private void drawButtomBg(Canvas canvas) {
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(ButtomBgColor);
        canvas.drawRect(0,topHeight+middleHeight,mWidth,mHeight,mPaint);
    }

    private static final int FormColor= Color.parseColor("#353E55");
    //画表格
    private void drawForm(Canvas canvas) {

        mPaint.setColor(FormColor);//表格线的颜色
        mPaint.setStrokeWidth(dp1);
        mPaint.setStyle(Paint.Style.FILL);

        //画横线表格
        for (int i = 0;i < TemHisChartView.Y_ITEMS_C.length;i++){
            float y1 = topHeight+i*middleItemHeght;
            canvas.drawLine(-xInit,y1,mWidth,y1,mPaint);
        }

        //画竖线表格
        int minColumn = (int) (mWidth/TemHisChartView.ItemIntervalWeight);
       // out("---minColumn="+minColumn+"---ItemIntervalWeight="+TemHisChartView.ItemIntervalWeight);
        if (datas!=null&&datas.size()+TemHisChartView.EdgeIntervalNum*2>=minColumn){
            minColumn=datas.size()+TemHisChartView.EdgeIntervalNum*2;
        }

        for (int i = 1;i <=minColumn;i++){
            float x1 = mWidth-i*TemHisChartView.ItemIntervalWeight+xInit;
            canvas.drawLine(x1,topHeight,x1,topHeight+middleHeight,mPaint);
        }




    }


    private static final int lineColor = Color.parseColor("#76A3F3");
    private void drawDatas(Canvas canvas, List<TemHisChartView.ItemBean> datas) {
        mPaint.setColor(lineColor);
        mPaint.setStrokeWidth(dp1);
        for (int i=0;i < datas.size();i++){
            drawLine(canvas,datas,i);
        }
    }


    //画线
    private void drawLine(Canvas canvas, List<TemHisChartView.ItemBean> datas, int i) {

       // LogUtils.i(TAG,"--drawLine--position = "+i+"--xInit = "+xInit+"--minXInit="+minXInit+"--maxXInit="+maxXInit);
        TemHisChartView.ItemBean itemBeanCur = datas.get(i);


        float valueT=itemBeanCur.value;
        if (itemBeanCur.value>41.7){
            valueT=41.7f;
        }else if (itemBeanCur.value<32.5){
            valueT=32.5f;
        }
        //画折线ok
        if (i+1 < datas.size()){
            mPaint.setColor(lineColor);
            TemHisChartView.ItemBean itemBeanNext = datas.get(i+1);
            float valueT2=itemBeanNext.value;
            if (valueT2>41.7){
                valueT2=41.7f;
            }else if (valueT2<32.5){
                valueT2=32.5f;
            }

            float startX = mWidth-(TemHisChartView.EdgeIntervalNum+i)*TemHisChartView.ItemIntervalWeight+xInit;
            float startY = (float) (topHeight+middleHeight*(1-(valueT-32.5)*1.0/9.0));

            float stopX = mWidth-(TemHisChartView.EdgeIntervalNum+i+1)*TemHisChartView.ItemIntervalWeight+xInit;
            float stopY = (float) (topHeight+middleHeight*(1-(valueT2-32.5)*1.0/9.0));

            canvas.drawLine(startX,startY,stopX,stopY,mPaint);
        }


        //画小圆圈点
        float cirX = mWidth-(TemHisChartView.EdgeIntervalNum+i)*TemHisChartView.ItemIntervalWeight+xInit;
        float cirY = (float) (topHeight+middleHeight*(1-(valueT-32.5)*1.0/9.0));



        if (valueT<=TemHisChartView.normalMaxTem&&valueT>TemHisChartView.normalMinTem){
            mPaint2.setStyle(Paint.Style.FILL);
            mPaint2.setColor(lineColor);
            canvas.drawCircle(cirX,cirY,dp1*3,mPaint2);
        }else {
            mPaint2.setColor(lineColor);
            mPaint2.setStyle(Paint.Style.STROKE);
            mPaint2.setStrokeWidth(dp1);
            canvas.drawCircle(cirX,cirY,dp1*3,mPaint2);

            mPaint2.setColor(huiBanColor);
            mPaint2.setStyle(Paint.Style.FILL);
            canvas.drawCircle(cirX,cirY, (float) (dp1*2.5),mPaint2);
        }


        if (selectIndex==i){
            if (valueT<=TemHisChartView.normalMaxTem&&valueT>TemHisChartView.normalMinTem){
                mPaint2.setStyle(Paint.Style.FILL);
                mPaint2.setColor(lineColor);
                canvas.drawCircle(cirX,cirY,dp1*6,mPaint2);
            }else {
                mPaint2.setColor(lineColor);
                mPaint2.setStyle(Paint.Style.STROKE);
                mPaint2.setStrokeWidth(dp1);
                canvas.drawCircle(cirX,cirY,dp1*6,mPaint2);

                mPaint2.setColor(huiBanColor);
                mPaint2.setStyle(Paint.Style.FILL);
                canvas.drawCircle(cirX,cirY, (float) (dp1*5.5),mPaint2);
            }
        }

       // mPaint.setColor(Color.parseColor("#ffffff"));
        mPaint.setColor(huiBanColor);
        mPaint.setTextSize(DipUtil.sp2px(getContext(),12));

        int[] dateWH = DipUtil.getTextWHeight(mPaint,itemBeanCur.date);
        float dateX = cirX-dateWH[0]/2;
        float dateY = topHeight+middleHeight+dp1*5+dateWH[1];



        canvas.drawText(itemBeanCur.date,dateX,dateY,mPaint);

        int[] timeWH = DipUtil.getTextWHeight(mPaint,itemBeanCur.time);
        float timeX =  cirX-timeWH[0]/2;
        float timeY = topHeight+middleHeight+dp1*10+dateWH[1]+timeWH[1];
        canvas.drawText(itemBeanCur.time,timeX,timeY,mPaint);

        //out("---日期="+itemBeanCur.date+"--X1="+dateX+"--Y1"+dateY);
        //out("---时间="+itemBeanCur.time+"--X1="+timeX+"--Y1"+timeY);
    }


    public void setDatas(List<TemHisChartView.ItemBean> datas) {
        this.datas = datas;
        initBaseData(true);
        invalidate();

    }

    public void addDatas(List<TemHisChartView.ItemBean> datas) {

        if (this.datas==null){
            this.datas = new ArrayList<>();
        }
        this.datas.addAll(0,datas);
        initBaseData(false);

        if (datas.size()>0){
            setSelectIndex(selectIndex,true);
        }else {
            invalidate();
        }

    }

    private void out(String msg){
        Log.i(TAG,msg);
    }


    //X轴的偏移量
    private float xInit;
    //最大偏移量
    private float maxXInit;
    //最小偏移量
    private float minXInit;

    //是否正在滑动
    private boolean isScrolling = false;
    private float startX;
    int mPosX;
    int mPosX_down;
    int mPosX_up;
    int mPosY;
    int mCurrentPosX;
    int mCurrentPosY;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isScrolling){
            return super.onTouchEvent(event);
        }

       // this.getParent().requestDisallowInterceptTouchEvent(true);//当该view获得点击事件，就请求父控件不拦截事件

        obtainVelocityTracker(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPosX = (int) event.getX();
                mPosX_down = (int) event.getX();
                mPosY = (int) event.getY();
                out("---onTouchEvent");
                startX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                out("---ACTION_MOVE");

                mCurrentPosX = (int) event.getX() - mPosX;
                mCurrentPosY = (int) event.getY() - mPosY;
                mPosX = (int) event.getX();
                mPosY = (int) event.getY();


               if (datas!=null){
                   if (TemHisChartView.ItemIntervalWeight * (datas.size()+2) > mWidth) {//当期的宽度不足以呈现全部数据
                       float dis = event.getX() - startX;
                       //dis
                       //由左到右滑动 dis>0
                       //由右到左滑动 dis<0
                       startX = event.getX();
                       LogUtils.i(TAG,"----MotionEvent.ACTION_MOVE---dis="+dis+"--xInit="+xInit+"--minXInit="+minXInit+"--maxXInit="+maxXInit);
                       if (xInit + dis< minXInit) {
                           xInit = minXInit;
                           LogUtils.i(TAG,"------A----xInit = minXInit");
                       } else if (xInit + dis > maxXInit) {
                           xInit = maxXInit;
                           LogUtils.i(TAG,"------B----xInit = maxXInit");
                       } else {
                           xInit = xInit + dis;
                           LogUtils.i(TAG,"------C----xInit = xInit + dis");
                       }

                     //  xInit = xInit + dis;
                       //LogUtils.i(TAG,"------C----xInit = xInit + dis");
                       invalidate();
                   }
               }
                break;
            case MotionEvent.ACTION_UP:
                mPosX_up = (int) event.getX();
                out("---ACTION_UP");
                clickAction(event);
                scrollAfterActionUp();
                listenerZYScorlling();
                this.getParent().requestDisallowInterceptTouchEvent(false);
                break;
            case MotionEvent.ACTION_CANCEL:
                out("---ACTION_CANCEL");
                this.getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }

        return true;
    }

    public TemHisChartView.ItemBean getSelectItem() {
        if (datas!=null&&datas.size()>0 && selectIndex>=0&&selectIndex<datas.size()){
            return datas.get(selectIndex);
        }
        return null;
    }


    public interface LeftRightScorllListener{
        void leftLoad();
        void rightLoad();
    }

    private LeftRightScorllListener mLeftRightScorllListener;

    public void setLeftRightScorllListener(LeftRightScorllListener mLeftRightScorllListener){
        this.mLeftRightScorllListener=mLeftRightScorllListener;
    }

    //监听左右加载滑动
    private void listenerZYScorlling() {
        int chazhi = mPosX_down-mPosX_up;
        LogUtils.i(TAG,"--listenerZYScorlling--mPosX_down="+mPosX_down+"--mPosX_up="+mPosX_up+"--chazhi="+chazhi+"--xInit="+xInit+"--minXInit="+minXInit+"--maxXInit="+maxXInit);

        int maxNum = 0;
        if (TemHisChartView.ItemIntervalWeight>0){
            maxNum = (int) (mWidth/TemHisChartView.ItemIntervalWeight);
        }


        if (chazhi<0 && xInit>maxXInit){
            //向左
            out("------向左1-加载");
            if (mLeftRightScorllListener!=null)mLeftRightScorllListener.leftLoad();
            return;
        }else if (chazhi<0 && xInit==maxXInit&&xInit!=0){
            //向右
            out("------向左2-加载");
            if (mLeftRightScorllListener!=null)mLeftRightScorllListener.leftLoad();
            return;
        }

        if (maxNum>0){
            if (chazhi<0 &&datas!=null&&datas.size()+2<=maxNum){
                out("------向左3-加载");
                if (mLeftRightScorllListener!=null)mLeftRightScorllListener.leftLoad();
                return;
            }
        }



    }


    /**
     * 点击X轴坐标或者折线节点
     */
    private void clickAction(MotionEvent event) {
        if (datas==null)return;
        int dp8 = dp1*8;
        float eventX = event.getX();
        float eventY = event.getY();
        for (int i = 0; i < datas.size(); i++) {
            //节点
            //画小圆圈点

            float valueT=datas.get(i).value;
            if (valueT>41.7){
                valueT=41.7f;
            }else if (valueT<32.5){
                valueT=32.5f;
            }
            float cirX = mWidth-(TemHisChartView.EdgeIntervalNum+i)*TemHisChartView.ItemIntervalWeight+xInit;
            float cirY = (float) (topHeight+middleHeight*(1-(valueT-32.5)*1.0/9.0));


            if (eventX >= cirX - dp8 && eventX <= cirX + dp8 &&
                    eventY >= cirY - dp8 && eventY <= cirY + dp8 && selectIndex != i) {//每个节点周围8dp都是可点击区域
                selectIndex = i;
                out("--------clickAction--A");
                invalidate();
                if (itemSelectListener!=null)itemSelectListener.selectChange(i,datas.get(i));
                return;
            }
            //X轴刻度
            int[] dateWH = DipUtil.getTextWHeight(mPaint,datas.get(i).date);
           // float dateX = cirX-dateWH[0]/2;
            //float dateY = topHeight+middleHeight+dp1*5+dateWH[1];

            int[] timeWH = DipUtil.getTextWHeight(mPaint,datas.get(i).time);
            //float timeX =  cirX-timeWH[0]/2;
            //float timeY = topHeight+middleHeight+dp1*10+dateWH[1]+timeWH[1];

            if (eventX >=cirX-dateWH[0]/2 - dp8 && eventX <= cirX+dateWH[0]/2 + dp8 / 2 &&
                    eventY >= topHeight+middleHeight+dp1*2 && eventY <= mHeight - dp1*2 && selectIndex != i) {
                selectIndex = i;
                out("---------clickAction--B");
                invalidate();
                if (itemSelectListener!=null)itemSelectListener.selectChange(i,datas.get(i));
            }
        }
    }

    //是否在ACTION_UP时，根据速度进行自滑动，没有要求，建议关闭，过于占用GPU
    private boolean isScroll = true;
    /**
     * 手指抬起后的滑动处理
     */
    private void scrollAfterActionUp() {
        if (!isScroll)
            return;
        final float velocity = getVelocity();
        out("velocity="+velocity);
        float scrollLength = maxXInit - minXInit;
        if (Math.abs(velocity) < 10000){//10000是一个速度临界值，如果速度达到10000，最大可以滑动(maxXInit - minXInit)
            scrollLength = (maxXInit - minXInit) * Math.abs(velocity) / 50000;
        }
        out("--velocity="+velocity+"--scrollLength="+scrollLength+"--Duration="+(long) (scrollLength / (maxXInit - minXInit) * 5000));
        ValueAnimator animator = ValueAnimator.ofFloat(0, scrollLength);
        animator.setDuration((long) (scrollLength / (maxXInit - minXInit) * 5000));//时间最大为1000毫秒，此处使用比例进行换算
        //animator.setInterpolator(new DecelerateInterpolator());
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                if (velocity < 0 && xInit > minXInit) {//向左滑动
                    if (xInit - value <= minXInit){
                        xInit = minXInit;
                    }else{
                        xInit = xInit - value;
                    }

                } else if (velocity > 0 && xInit < maxXInit) {//向右滑动
                    if (xInit + value >= maxXInit){
                        xInit = maxXInit;
                    }else{
                        xInit = xInit + value;
                    }

                }
               // out("--------onAnimationUpdate---invalidate");
                invalidate();
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                isScrolling = true;
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                isScrolling = false;
            }

            @Override
            public void onAnimationCancel(Animator animator) {
                isScrolling = false;
            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        animator.start();

    }
    //速度检测器
    private VelocityTracker velocityTracker;
    /**
     * 获取速度
     */
    private float getVelocity() {
        if (velocityTracker != null) {
            velocityTracker.computeCurrentVelocity(1000);
            return velocityTracker.getXVelocity();
        }
        return 0;
    }

    /**
     * 获取速度跟踪器
     */
    private void obtainVelocityTracker(MotionEvent event) {
        if (!isScroll)
            return;
        if (velocityTracker == null) {
            velocityTracker = VelocityTracker.obtain();
        }
        velocityTracker.addMovement(event);
    }



    private TemHisChartView.ItemSelectListener itemSelectListener;

    public void setItemSelectListener(TemHisChartView.ItemSelectListener itemSelectListener) {
        this.itemSelectListener = itemSelectListener;
    }
}
